﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.XPath;
using System.IO;
using System.Configuration;
using eCitizen.DataContracts;
using eCitizen.DataAccess;
using eCitizen.eAlerts.Constants;

namespace eCitizen.eAlerts.Utilities
{
    public class FileManager
    {
        private static List<SftpConfiguration> _sftpConfigurations;
        public List<SftpConfiguration> SftpConfigurations { get { return _sftpConfigurations; } }
        private string configurationFileUrl;
        public FileManager()
        {
            configurationFileUrl = AppKeyConstants.SftpFolderUrl;
            if (_sftpConfigurations == null) LoadConfigurations();
            PrepareWorkingDirectories();
        }


        // Temporarily using Local IO, change it to sFTP Later
        public List<ServiceRequest> GeteAlertRequestFiles(SftpConfiguration fileConfiguration)
        {

            List<ServiceRequest> filePairs = new List<ServiceRequest>();
            // 1. Get all files in the Agency Inbox {Only .DAT files}
            string directoryUrl = fileConfiguration.GetLocalInboxFolder();

            if (Directory.Exists(directoryUrl))
            {
                
                List<string> fileEntries = Directory.GetFiles(directoryUrl, ServiceConstants.FileFilterFormats.eAlertsDataFileFormat).ToList();

                // 2. Iterate the list of the files
                if (fileEntries != null && fileEntries.Count > 0)
                {
                    foreach (string requestFile in fileEntries)
                    {
                        string requestFileName = Path.GetFileNameWithoutExtension(requestFile);
                        string requestFilePath = Path.GetDirectoryName(requestFile);
                        string checkSumFile = string.Format("{0}\\{1}.NUM", requestFilePath, requestFileName);

                        if (File.Exists(requestFile) && File.Exists(checkSumFile))
                        {
                            ServiceRequest currentRequest = new ServiceRequest();

                            // Get the request file 

                            currentRequest.RequestFileName = Path.GetFileName(requestFile);
                            currentRequest.RequestFileFullPath = requestFile;
                            currentRequest.RequestFile = new StreamReader(requestFile);
                            // Get the check sum file
                            currentRequest.ChecksumFileName = Path.GetFileName(checkSumFile);
                            currentRequest.ChecksumFileFullPath = checkSumFile;
                            currentRequest.ChecksumFile = new StreamReader(checkSumFile);


                            ServiceInfo currentService = new ServiceInfo();
                            currentService.ProcessFileName = Path.GetFileName(requestFile);
                            currentService.ServiceId = fileConfiguration.Service;
                            currentService.ServiceStartDatetime = System.DateTime.Now;
                            currentService.CurrentServiceType = ServiceType.SendAlertService;

                            currentRequest.CurrentServiceInfo = currentService;

                            filePairs.Add(currentRequest);

                        }
                        else
                        {
                            // Cannot find the full file pair
                            ErrorLogManager errorLogManager = new ErrorLogManager();
                            errorLogManager.CreateErrorLogfile(fileConfiguration,ServiceType.SendAlertService, ErrorMessageConstants.SendAlertService_ChecksumFileNotFound);
                        }

                    }

                }

            }
            return filePairs;
        }
        
        public List<ServiceRequest> GetReportFiles(SftpConfiguration fileConfiguration)
        {
            List<ServiceRequest> files = new List<ServiceRequest>();
            List<string> fileEntries = new List<string>();

            string directory = fileConfiguration.GetLocalSmsOutboxFolder();
            

            if (Directory.Exists(directory))
            {

                fileEntries = Directory.GetFiles(directory).Where(s => ServiceConstants.FileFilterFormats.ReportFileFormat.ToUpper().Contains(Path.GetExtension(s).ToUpper())).ToList();

                foreach (string requestFile in fileEntries)
                {

                    ServiceRequest currentRequest = new ServiceRequest();

                    currentRequest.RequestFileName = Path.GetFileName(requestFile);
                    currentRequest.RequestFileFullPath = requestFile;
                    currentRequest.RequestFile = new StreamReader(requestFile);

                    ServiceInfo currentService = new ServiceInfo();
                    currentService.ProcessFileName = Path.GetFileName(requestFile);
                    currentService.ServiceId = fileConfiguration.Service;
                    currentService.ServiceStartDatetime = System.DateTime.Now;
                    currentService.CurrentServiceType = ServiceType.SendReportService;

                    currentRequest.CurrentServiceInfo = currentService;

                    files.Add(currentRequest);
                }
                
            }

            return files;
        }

        public void ArchiveSendAlertServiceFiles(SftpConfiguration fileConfiguration)
        {

            string localInboxFolder = fileConfiguration.GetLocalInboxFolder();
            string localSmsInboxFolder = fileConfiguration.GetLocalSmsInboxFolder();

            string localArchiveInboxFolder = fileConfiguration.GetLocalArchieveInboxFolder();
            string localSmsArchiveInboxFolder = fileConfiguration.GetLocalSmsArchieveInboxFolder();


            string localErrorFolder = fileConfiguration.GetLocalOutboxFolder();
            string localErrorArchiveFolder = fileConfiguration.GetLocalArchieveOutboxFolder();

            List<string> fileEntries = new List<string>();

            // 1. Archieve Request Files
            fileEntries = Directory.GetFiles(localInboxFolder).Where(s => ServiceConstants.FileFilterFormats.eAlertsFilePairFormat.ToUpper().Contains(Path.GetExtension(s).ToUpper())).ToList();

            foreach (string file in fileEntries)
            {
                if (!Directory.Exists(localArchiveInboxFolder)) Directory.CreateDirectory(localArchiveInboxFolder);

                string destinationFile = string.Format("{0}\\{1}", localArchiveInboxFolder, Path.GetFileName(file));
                if (File.Exists(destinationFile)) File.Delete(destinationFile);

                File.Move(file, destinationFile);
            }
            
            // 2. Archieve OneSms Request Files

            fileEntries = Directory.GetFiles(localSmsInboxFolder).Where(s => ServiceConstants.FileFilterFormats.OneSmsRequestFileFormat.ToUpper().Contains(Path.GetExtension(s).ToUpper())).ToList();

            foreach (string file in fileEntries)
            {
                if (!Directory.Exists(localSmsArchiveInboxFolder)) Directory.CreateDirectory(localSmsArchiveInboxFolder);

                string destinationFile = string.Format("{0}\\{1}", localSmsArchiveInboxFolder, Path.GetFileName(file));
                if (File.Exists(destinationFile)) File.Delete(destinationFile);

                File.Move(file, destinationFile);
            }

            // 3. Move eAlertsService Error log files

            fileEntries = Directory.GetFiles(localErrorFolder).Where(s => ServiceConstants.FileFilterFormats.eAlertsErrorLogFormat.ToUpper().Contains(Path.GetExtension(s).ToUpper())).ToList();
            
            foreach (string file in fileEntries)
            {
                if (!Directory.Exists(localErrorArchiveFolder)) Directory.CreateDirectory(localErrorArchiveFolder);

                string destinationFile = string.Format("{0}\\{1}", localErrorArchiveFolder, Path.GetFileName(file));
                if (File.Exists(destinationFile)) File.Delete(destinationFile);

                File.Move(file, destinationFile);
            }

        }

        public void ArchiveSendReportFiles(SftpConfiguration fileConfiguration)
        {

            string localReportFolder = fileConfiguration.GetLocalOutboxFolder();
            string localSmsReportFolder = fileConfiguration.GetLocalSmsOutboxFolder();

            string localReportArchiveFolder = fileConfiguration.GetLocalArchieveOutboxFolder();
            string localSmsReportArchiveFolder = fileConfiguration.GetLocalSmsArchieveOutboxFolder();
            List<string> fileEntries = new List<string>();

            // 1. Archieve Subscriber, Sms, Email Report Files
            fileEntries = Directory.GetFiles(localReportFolder).Where(s => ServiceConstants.FileFilterFormats.FullReportFileFormat.ToUpper().Contains(Path.GetExtension(s).ToUpper())).ToList();

            foreach (string file in fileEntries)
            {
                if (!Directory.Exists(localReportArchiveFolder)) Directory.CreateDirectory(localReportArchiveFolder);

                string destinationFile = string.Format("{0}\\{1}", localReportArchiveFolder, Path.GetFileName(file));
                if (File.Exists(destinationFile)) File.Delete(destinationFile);

                File.Move(file, destinationFile);
            }

            fileEntries = Directory.GetFiles(localSmsReportFolder).Where(s => ServiceConstants.FileFilterFormats.ReportFileFormat.ToUpper().Contains(Path.GetExtension(s).ToUpper())).ToList();

            foreach (string file in fileEntries)
            {
                if (!Directory.Exists(localSmsReportArchiveFolder)) Directory.CreateDirectory(localSmsReportArchiveFolder);

                string destinationFile = string.Format("{0}\\{1}", localReportArchiveFolder, Path.GetFileName(file));
                if (File.Exists(destinationFile)) File.Delete(destinationFile);

                File.Move(file, destinationFile);
            }
        }

        
        // This method will load all of the Agency folders as configurations
        private void LoadConfigurations()
        {
            _sftpConfigurations = new List<SftpConfiguration>();
            ConfigurationService configService = new ConfigurationService();

            _sftpConfigurations = configService.LoadConfigurations();

            foreach (SftpConfiguration config in _sftpConfigurations)
            {
                config.RootDirectoryUrl = AppKeyConstants.SftpFolderUrl;
                config.ArchieveFolderUrl = ServiceConstants.SftpConfigruationConstants.ArchiveFolder;
                config.OneSmsFolderUrl = ServiceConstants.SftpConfigruationConstants.OneSmsFolder;
                config.InboxUrl = ServiceConstants.SftpConfigruationConstants.InboxUrl;
                config.OutboxUrl = ServiceConstants.SftpConfigruationConstants.OutboxUrl;
            }

        }

        private void PrepareWorkingDirectories()
        {
            foreach (SftpConfiguration config in _sftpConfigurations)
            {
                if (!Directory.Exists(config.GetLocalArchieveInboxFolder())) Directory.CreateDirectory(config.GetLocalArchieveInboxFolder());
                if (!Directory.Exists(config.GetLocalArchieveOutboxFolder())) Directory.CreateDirectory(config.GetLocalArchieveOutboxFolder());
                if (!Directory.Exists(config.GetLocalInboxFolder())) Directory.CreateDirectory(config.GetLocalInboxFolder());
                if (!Directory.Exists(config.GetLocalOutboxFolder())) Directory.CreateDirectory(config.GetLocalOutboxFolder());
                if (!Directory.Exists(config.GetLocalSmsArchieveInboxFolder())) Directory.CreateDirectory(config.GetLocalSmsArchieveInboxFolder());
                if (!Directory.Exists(config.GetLocalSmsArchieveOutboxFolder())) Directory.CreateDirectory(config.GetLocalSmsArchieveOutboxFolder());
                if (!Directory.Exists(config.GetLocalSmsInboxFolder())) Directory.CreateDirectory(config.GetLocalSmsInboxFolder());
                if (!Directory.Exists(config.GetLocalSmsOutboxFolder())) Directory.CreateDirectory(config.GetLocalSmsOutboxFolder());
            }
        }



    }
}
